﻿using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;

namespace OrbitOne.SharePoint.Provision.WebParts
{
    [Guid("5de12d60-d168-4abf-b61d-4888b99d5355"),
 ToolboxData("<{0}:SiteCollectionADConnectionStringWebPart runat=server></{0}:SiteCollectionADConnectionStringWebPart>"),
    XmlRoot(Namespace = "OrbitOne.Provision.WebParts")]
    public class SiteCollectionADSettingWebPart : GeneralWebPart
    {
        
       
        
        HtmlInputText _connectionStringValue;
        HtmlInputText _siteCollectionOUNameValue;
        HtmlTextArea _status;
        HtmlButton _goButton;
        public SiteCollectionADSettingWebPart()
        {
            ExportMode = WebPartExportMode.All;
           
        }



        protected override void CreateChildControls()
        {

           
            
            _connectionStringValue = new HtmlInputText();
            _connectionStringValue.Size = 80;
            _siteCollectionOUNameValue = new HtmlInputText();
          
            _goButton = new HtmlButton();
            _status = new HtmlTextArea();

            // Button text
            _goButton.InnerText = "Save";

            // Add an event handler when the button is clicked
            _goButton.ServerClick += new EventHandler(_goButton_ServerClick);

            // Add the controls to the web part

            Controls.Add(_connectionStringValue);
            Controls.Add(_siteCollectionOUNameValue);
            Controls.Add(_goButton);
            Controls.Add(_status);
        }

        public void _goButton_ServerClick(object sender, EventArgs e)
        {
            string invalidInfo;
            if(!CheckInput(out  invalidInfo))
            {
                _status.Value = string.Format("The input value for {0} is not valid.", invalidInfo);
                _failure = true;
                return;
            }
            if (!ValidateInput(out  invalidInfo))
            {
                _status.Value = invalidInfo;
                _failure = true;
                return;
            }
            try
            {
               
                using (new ElevationManager())
                {


                   

                    if (_rootWeb.AllProperties.Contains(Constants.SITE_COLLECTION_LADP_KEY))
                    {
                        _rootWeb.AllProperties[Constants.SITE_COLLECTION_LADP_KEY] = _connectionStringValue.Value.Trim();
                    }
                    else
                    {
                        _rootWeb.AllProperties.Add(Constants.SITE_COLLECTION_LADP_KEY, _connectionStringValue.Value.Trim());
                    }


                    if (_rootWeb.AllProperties.Contains(Constants.SITE_COLLECTION_AD_OU_NAME))
                    {
                        _rootWeb.AllProperties[Constants.SITE_COLLECTION_AD_OU_NAME] = _siteCollectionOUNameValue.Value.Trim();
                    }
                    else
                    {
                        _rootWeb.AllProperties.Add(Constants.SITE_COLLECTION_AD_OU_NAME, _siteCollectionOUNameValue.Value.Trim());
                    }



                    _rootWeb.Update();
                }
                _status.Value = "Your settings has been successfully changed.";
                 _failure = false;
               
               

            }
            catch (Exception ex)
            {
                _status.Value = ex.Message;
                _failure = true;
            }
        }

        private bool CheckInput(out string info)
        {
            info = string.Empty;
            bool result = true;
            if(!_connectionStringValue.Value.Trim().Contains("LDAP://"))
            {
                result = false;
                info = "\'Connection string\'";
            }
            if(string.IsNullOrEmpty(_siteCollectionOUNameValue.Value.Trim()))
            {
                result = false;
                info = info + (string.IsNullOrEmpty(info) ? string.Empty : " and ") + "\'Orgnization unit\'";
            }
           
           return  result;
            
        }
        private bool ValidateInput(out string info)
        {
            info = string.Empty;
            bool result = true;
            if (!ADProvisioning.IsValidConnectionString(_connectionStringValue.Value.Trim()))
            {
                result = false;
                info = "Cannot connect using this connection string.";
                return result;
            }
            if(!ADProvisioning.IsOrganisationUnitExist(_siteCollectionOUNameValue.Value.Trim(),_connectionStringValue.Value.Trim()))
            {
                result = false;
                info =  "The organization unit does not exist.";
            }
            return result;
        }

        #region Render Controls


        protected override void OnPreRender(EventArgs e)
        {
            // If this web part is being drawn and no failure has occured,
            //  the make sure textbox values are cleared
            if (!_failure)
            {
                // Clear the fields
              
                _connectionStringValue.Value =
                     _rootWeb.AllProperties.Contains(Constants.SITE_COLLECTION_LADP_KEY) ? _rootWeb.AllProperties[Constants.SITE_COLLECTION_LADP_KEY].ToString() : string.Empty; ;

                _siteCollectionOUNameValue.Value =
                    _rootWeb.AllProperties.Contains(Constants.SITE_COLLECTION_AD_OU_NAME) ? _rootWeb.AllProperties[Constants.SITE_COLLECTION_AD_OU_NAME].ToString() : string.Empty; ;
               
            }

            base.OnPreRender(e);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            // TODO: add custom rendering code here.
            // writer.Write("Output HTML");
            BuildWSSUI(writer);
        }


        
        private void BuildWSSUI(HtmlTextWriter output)
        {
            string messageColor;

            // Write any error or status messages
            if (_failure)
            {
                messageColor = "Red";
            }
            else
            {
                messageColor = "Green";
            }

            BuildStatus(_status.Value.ToString(), messageColor, output);

            // Start the table
            output.Write("<TABLE border='0' width='100%' cellspacing='0' cellpadding='0'>");

            // Build a row for each control



            BuildRow("Active Directory Connection String", "Enter the LDAP connection string where new users accounts for this site collection should be stored. Format: LDAP://SERVERNAME/OU=OrganisationUnitName, DC=DomainName, DC=local", _connectionStringValue, output);
            LineBreak("ActiveDirectoryConnectionString", output);

            BuildRow("Organisation Unit", "Enter the Active Directory OU where new user accounts for this site should be stored. The OU needs to exist and it should be a child of the OU defined in the connection string (see above).", _siteCollectionOUNameValue, output);
            LineBreak("OrganisationUnit", output);

            // Draw the buttons
            BuildButton(_goButton, output);
            LineBreak("EndGoButton", output, 2);

            // End the table
            output.Write("</TABLE>");

        }



       
        #endregion Render Controls
    }
}
